package com.cloud.salon.gateway.component.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloud.salon.gateway.bean.UserDetailsServiceImpl;
import com.cloud.salon.gateway.util.TokenAuthenticationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/*
 * 自定义JWT Token验证过滤器，用于权限控制
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	UserDetailsServiceImpl userDetailsService;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//设置返回ContentType
		response.setContentType("application/json;charset=utf-8");
		//获取Token加密的用户名
        String[] tokenInfo = TokenAuthenticationUtil.parseToken((HttpServletRequest)request);

        String username = tokenInfo != null? tokenInfo[0]: null;
        String authoritiesStr = tokenInfo != null? tokenInfo[1]: null;
		
		UserDetails userDetails;
		Authentication authentication = null;
		
		if(username != null) {
			//通过用户名获取该用户UserDetails类
			userDetails = userDetailsService.loadUserByUsername(username);
			
			if (userDetails != null) {
				
				//获取该用户所具有的的权限
				//List<GrantedAuthority> authorities = userDetails.getAuthorities();
				
				//获取Token信息中的权限信息
				List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesStr);
				
				//构建该用户的Token令牌
                authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
            }
		}
		
		//保存令牌
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
	}
}
